package com.yami.shop.cp.api.controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yami.shop.bean.app.dto.ShopCartAmountDto;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.Sku;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.util.Arith;
import com.yami.shop.cp.comment.dto.CollaborativePurchaseShopCartItemDto;
import com.yami.shop.cp.comment.enums.CollaborativePurchaseBasketEnum;
import com.yami.shop.cp.comment.model.CollaborativePurchase;
import com.yami.shop.cp.comment.model.CollaborativePurchaseBasket;
import com.yami.shop.cp.comment.param.ChangeSubmitPersonShopCartParam;
import com.yami.shop.cp.comment.service.CollaborativePurchaseBasketService;
import com.yami.shop.cp.comment.service.CollaborativePurchaseService;
import com.yami.shop.cp.comment.service.CollaborativeSubmitPersonService;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SkuService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 协同采购提报人购物车 前端控制器
 * </p>
 *
 * @author xch
 * @since 2021-06-29
 */
@RestController
@RequestMapping("/p/cp/basket")
@AllArgsConstructor
public class CollaborativePurchaseBasketController {

    private CollaborativePurchaseBasketService collaborativePurchaseBasketService;
    private ProductService productService;
    private SkuService skuService;
    private CollaborativePurchaseService collaborativePurchaseService;
    private CollaborativeSubmitPersonService collaborativeSubmitPersonService;

    @PostMapping("/sp/submit")
    @ApiOperation(value = "提报人提交当前协助采购清单的全部商品")
    public ResponseEntity<String> submit(@RequestBody String collaborativePurchaseId) {
        String mobile = SecurityUtils.getSubmitPerson().getMobile();

        // 获取协同保单提报后的信息
        List<CollaborativePurchaseShopCartItemDto> collaborativePurchaseSubmitShopCartItems = collaborativePurchaseBasketService.getShopCartItemsByCollaborativePurchaseId(collaborativePurchaseId);

        // 获取协同采购单已提报的商品总额
        double totalSubmit = 0.0;
        for (CollaborativePurchaseShopCartItemDto collaborativePurchaseShopCartItemDto : collaborativePurchaseSubmitShopCartItems) {
            totalSubmit = Arith.add(collaborativePurchaseShopCartItemDto.getProductTotalAmount(), totalSubmit);
        }

        // 获取提报人提报的商品总额
        List<CollaborativePurchaseShopCartItemDto> collaborativePurchaseShopCartItems = collaborativePurchaseBasketService.getSubmitPersonShopCartItems(mobile, collaborativePurchaseId);
        double total = 0.0;
        for (CollaborativePurchaseShopCartItemDto collaborativePurchaseShopCartItemDto : collaborativePurchaseShopCartItems) {
            total = Arith.add(collaborativePurchaseShopCartItemDto.getProductTotalAmount(), total);
        }
        CollaborativePurchase collaborativePurchase = collaborativePurchaseService.getById(collaborativePurchaseId);
        // 判断是否超过了协同采购单的最大金额
        if (collaborativePurchase.getMaxMoney().doubleValue() > 0 && total > Arith.sub(collaborativePurchase.getMaxMoney().doubleValue(), totalSubmit)) {
            return ResponseEntity.ok(I18nMessage.getMessage("yami.submit.collaborative.purchase.basket.amount.big.error"));
        }
        // 判断是否超出时间限制
        if (LocalDateTime.now().isAfter(collaborativePurchase.getEndTime())) {
            return ResponseEntity.ok(I18nMessage.getMessage("yami.submit.collaborative.purchase.basket.exceed.end.time"));
        }

        // 修改采购单提报人状态
        collaborativeSubmitPersonService.updateCSPByCPIdAndMobile(collaborativePurchaseId, mobile);
        // 修改提报人当前协同采购单购物车的状态
        collaborativePurchaseBasketService.update(new LambdaUpdateWrapper<CollaborativePurchaseBasket>()
                .set(CollaborativePurchaseBasket::getStatus, CollaborativePurchaseBasketEnum.SUBMIT.getValue())
                .eq(CollaborativePurchaseBasket::getCollaborativePurchaseId, collaborativePurchaseId)
                .eq(CollaborativePurchaseBasket::getMobile, mobile));

        return ResponseEntity.ok(I18nMessage.getMessage("yami.submit.collaborative.purchase.basket.successfully"));
    }

    @DeleteMapping("/sp/deleteItem")
    @ApiOperation(value = "通过购物车id删除用户购物车物品")
    public ResponseEntity<String> deleteItem(@RequestBody List<Long> basketIds) {
        collaborativePurchaseBasketService.deleteSubmitPersonShopShopCartItemsByBasketIds(basketIds);
        return ResponseEntity.ok(I18nMessage.getMessage("yami.collaborative.purchase.basket.delete.successfully"));
    }

    @GetMapping("/sp/info/{id}")
    @ApiOperation(value = "获取当前协同采购单当前提报人购物车详情")
    public ResponseEntity<List<CollaborativePurchaseShopCartItemDto>> infoByCollaborativePurchaseId(@PathVariable("id") String collaborativePurchaseId) {
        String mobile = SecurityUtils.getSubmitPerson().getMobile();
        List<CollaborativePurchaseShopCartItemDto> collaborativePurchaseShopCartItems = collaborativePurchaseBasketService.getSubmitPersonShopCartItems(mobile, collaborativePurchaseId);
        return ResponseEntity.ok(collaborativePurchaseShopCartItems);
    }

    @GetMapping("/sp/prodCountAndMoney/{id}")
    @ApiOperation(value = "获取当前协同采购单当前提报人购物车商品总数和金额")
    public ResponseEntity<ShopCartAmountDto> prodCountAndMoneyByCollaborativePurchaseId(@PathVariable("id") String collaborativePurchaseId) {
        String mobile = SecurityUtils.getSubmitPerson().getMobile();
        List<CollaborativePurchaseShopCartItemDto> collaborativePurchaseShopCartItems = collaborativePurchaseBasketService.getSubmitPersonShopCartItems(mobile, collaborativePurchaseId);

        double total = 0.0;
        int count = 0;
        for (CollaborativePurchaseShopCartItemDto collaborativePurchaseShopCartItemDto : collaborativePurchaseShopCartItems) {
            count = collaborativePurchaseShopCartItemDto.getProdCount() + count;
            total = Arith.add(collaborativePurchaseShopCartItemDto.getProductTotalAmount(), total);
        }
        ShopCartAmountDto shopCartAmountDto = new ShopCartAmountDto();
        shopCartAmountDto.setCount(count);
        shopCartAmountDto.setTotalMoney(total);
        shopCartAmountDto.setFinalMoney(shopCartAmountDto.getTotalMoney());
        return ResponseEntity.ok(shopCartAmountDto);
    }


    @PostMapping("/sp/changeItem")
    @ApiOperation(value = "添加、修改用户购物车物品", notes = "通过商品id(prodId)、skuId、店铺Id(shopId),添加/修改用户购物车商品，并传入改变的商品个数(count)，" +
            "当count为正值时，增加商品数量，当count为负值时，将减去商品的数量，当最终count值小于0时，会将商品从购物车里面删除")
    public ResponseEntity<String> addItem(@Valid @RequestBody ChangeSubmitPersonShopCartParam param) {
        if (param.getCount() == 0) {
            // 输入更改数量
            return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.shopCart.enter.num"));
        }
        String mobile = SecurityUtils.getSubmitPerson().getMobile();
        List<CollaborativePurchaseShopCartItemDto> collaborativePurchaseShopCartItems = collaborativePurchaseBasketService.getSubmitPersonShopCartItems(mobile, param.getCollaborativePurchaseId());
        Product prodParam = productService.getProductByProdId(param.getProdId(), I18nMessage.getDbLang());
        Sku skuParam = skuService.getSkuBySkuId(param.getSkuId(), I18nMessage.getDbLang());

        // 当商品状态不正常时，不能添加到购物车
        if (prodParam.getStatus() != 1 || skuParam.getStatus() != 1) {
            String message = I18nMessage.getMessage("yami.product");
            String takeOff = I18nMessage.getMessage("yami.shopCart.take.off");
            // 商品已下架
            throw new YamiShopBindException(message + takeOff);
        }
        // 当商品为预售商品时，不能添加到购物车
        if (prodParam.getPreSellStatus() != null && Objects.equals(prodParam.getPreSellStatus(), 1)) {
            // 预售商品不能加入购物车
            throw new YamiShopBindException("yami.prod.pre.sell");
        }

        for (CollaborativePurchaseShopCartItemDto shopCartItemDto : collaborativePurchaseShopCartItems) {
            if (Objects.equals(param.getSkuId(), shopCartItemDto.getSkuId())) {
                CollaborativePurchaseBasket collaborativePurchaseBasket = new CollaborativePurchaseBasket();
                collaborativePurchaseBasket.setBasketCount(param.getCount() + shopCartItemDto.getProdCount());
                collaborativePurchaseBasket.setCollaborativePurchaseBasketId(shopCartItemDto.getCollaborativePurchaseBasketId());
                // 防止购物车变成负数
                if (collaborativePurchaseBasket.getBasketCount() <= 0) {
                    collaborativePurchaseBasketService.removeById(collaborativePurchaseBasket.getCollaborativePurchaseBasketId());
                    return ResponseEntity.ok().build();
                }
                // 当sku实际库存不足时，不能添加到购物车
                if (skuParam.getStocks() < collaborativePurchaseBasket.getBasketCount() && param.getCount() > 0) {
                    // 商品库存不足
                    String msg = I18nMessage.getMessage("yami.insufficient.inventory");
                    return ResponseEntity.ok(msg);
                }
                collaborativePurchaseBasketService.update(new LambdaUpdateWrapper<CollaborativePurchaseBasket>()
                        .set(CollaborativePurchaseBasket::getBasketCount, collaborativePurchaseBasket.getBasketCount())
                        .eq(CollaborativePurchaseBasket::getCollaborativePurchaseBasketId, collaborativePurchaseBasket.getCollaborativePurchaseBasketId()));
                return ResponseEntity.ok(I18nMessage.getMessage("yami.activity.add.success"));
            }
        }
        // 防止购物车已被删除的情况下,添加了负数的商品
        if (param.getCount() < 0) {
            // 商品已从购物车移除
            return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.product.remove"));
        }
        // 当sku实际库存不足时，不能添加到购物车
        if (skuParam.getStocks() < param.getCount() && param.getCount() > 0) {
            // 库存不足
            return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.insufficient.inventory"));
        }

        // 所有都正常时
        collaborativePurchaseBasketService.addSubmitPersonShopCartItem(param, mobile);
        // 添加成功
        return ResponseEntity.ok(I18nMessage.getMessage("yami.activity.add.success"));
    }
}
